Ex012, Accessing records programmatically


This example illustrates accessing records and fields without using data control
components such as DBEdit boxes memos, and other data controls. In this example we
want to read records from Phone table and save it in a text file.

If you do not create Phone table refere to
Ex007 then create Phone table and enter
data on it.

Exercise 012: Accessing records programmatically

1. Drop a Table. Select DBDEMOS at DatabaseName property. Select Phone at TableName
property.
2. Drop a
Button and write this code at OnClick event:

var
F: TextFile;
begin
AssignFile(F, 'Phone.txt');
Rewrite(F);
Writeln(F, 'Number            Name            Address             Notes');
Writeln(F, '------------------------------------------------------------');
Table1.Open;
Table1.First;
while not
Table1.Eof do
begin
  Writeln(F,
Table1.FieldByName('Number').AsString, '     ',
   
Table1.FieldByName('Name').AsString, '     '+
     
Table1.FieldByName('Address').AsString+'     '+
       
Table1.FieldByName('Notes').AsString);
 
Table1.Next;  // move to next record
end; // while
Writeln(F, '------------------------------------------------------------');
CloseFile(F);
Table1.Close;

3. Run program, click the button then close form. After that you can open
'Phone.txt'
by any text editor or by Delphi editor by pressing
Ctrl+Enter at 'Phone.txt' string.


Above example illustrates how can we read data from a table using Table object directly.
The second one illustrates how to append or modify existed data without using data
controls.

In this example we want to add records to phone table using standard edit boxes.

1. Drop a Table, select 'DBDEMOS' DatabaseName, and phone.db in TableName.
2. Drop three
Edit boxes from standard page, name it 'edName', 'edNumber', and 'edAddress'.
3. Drop a
Memo from standard page, name it 'meNotes'.
4. Drop two buttons, caption one
'Add', and the other 'Save'.
5. At form's OnCreate event write:

 Table1.Open;

6. At
Add button OnClick event write:

 edName.Clear;
edNumber.Clear;
edAddress.Clear;
meNotes.Clear;
Table1.
Append;


7. At Save button OnClick event write:

 Table1.Edit;
Table1.FieldByName('Name').AsString:=
  edName.Text;
Table1.FieldByName('Number').AsString:=
  edNumber.Text;
Table1.FieldByName('Address').AsString:=
  edAddress.Text;
Table1.FieldByName('Notes').AsString:=
  meNotes.Text;
Table1.
Post;

8. Run the application.


You can add a
DataSource and DBGrid to view new added records, or you can goto Database
Desktop to see if new records has been added to
phone.db table.